package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.base.SupportToolbarFragement;
import com.chcit.mobile.app.utils.DialogUtil;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.model.entity.BpartnerBean;
import com.chcit.mobile.mvp.model.entity.ReceiveBean;
import com.chcit.mobile.mvp.model.entity.Statu;
import com.chcit.mobile.mvp.ui.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.ui.adapter.ReceiveAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.component.DaggerReceiveComponent;
import com.chcit.mobile.di.module.ReceiveModule;
import com.chcit.mobile.mvp.contract.ReceiveContract;
import com.chcit.mobile.mvp.presenter.ReceivePresenter;
import com.chcit.mobile.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ReceiveFragment extends ScanFragment<ReceivePresenter> implements ReceiveContract.View {
    @BindView(R.id.et_receive_list_package_document_no)
    SuperEditText etReceiveListPackageDocumentNo;
    @BindView(R.id.bt_receive_list_query)
    Button btQuery;
    @BindView(R.id.ckb_select_all)
    CheckBox selectAll;
    @BindView(R.id.bt_batch_confirm)
    Button btBatchConfirm;
    @BindView(R.id.linear_layout_show)
    LinearLayoutCompat mLinearLayout;
    @BindView(R.id.pr_receive_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_show_select)
    TextView tvShowSelect;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    ReceiveAdapter mAdapter;
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tietProductName;
    private BpartnerBean bpartnerBean;
    private String headers[] = {"选择供应商", "输入商品", "一周内","入库类型"};
    private int dateTime = 1;//选择的日期 0没选择  1-1月内  2-2月内  3-3月内
    private ReceiveBean receiveBean;
    private int REQUEST_CODE = getClass().hashCode();
    private String asnType = "";
    public static ReceiveFragment newInstance() {
        ReceiveFragment fragment = new ReceiveFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveModule(new ReceiveModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_receive, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        mCommonToolbar.setTitle("收货");
        mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        initDropDownMenu();

    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(getContext());
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarTextWithLong(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etReceiveListPackageDocumentNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mAdapter.checkAll();
                } else {
                    mAdapter.cancelAll();
                }
            }
        });

    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean("不限", ""));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });
        //商品选择
        final View constellationView = getLayoutInflater().inflate(R.layout.custom_layout, null);
        tietProductName = constellationView.findViewById(R.id.constellation);
        TextView ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tietProductName.getText().toString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
            }
        });

        //日期选择
        final ListView dateView = new ListView(getContext());
        List<String> dates = Arrays.asList("不限", "一周内", "二周内", "三周内");
        final GirdDropDownAdapter<String> dateAdapter = new GirdDropDownAdapter<String>(getContext(), dates);
        dateAdapter.setCheckItem(1);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            dateTime = position;
            mDropDownMenu.setTabText(position == 0 ? "选择日期" : dates.get(position));
            mDropDownMenu.closeMenu();
        });

        //入库类型选择
        final ListView receiveTypeView = new ListView(getContext());
        List<Statu> receiveTypes = new ArrayList<>();
        receiveTypes.add(new Statu("", "不限"));
        receiveTypes.add(new Statu("MV", "调拨入库"));
        receiveTypes.add(new Statu("SR", "销退入库"));
        final GirdDropDownAdapter<Statu> receiveTypeAdapter = new GirdDropDownAdapter<Statu>(getContext(), receiveTypes);
        receiveTypeView.setDividerHeight(0);
        receiveTypeView.setAdapter(receiveTypeAdapter);
        receiveTypeView.setOnItemClickListener((parent, view, position, id) -> {
            receiveTypeAdapter.setCheckItem(position);
            asnType = receiveTypes.get(position).getId();
            mDropDownMenu.setTabText(position == 0 ? headers[3] : receiveTypes.get(position).getName());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        popupViews.add(receiveTypeView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("筛选条件");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.BOTTOM);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 14);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView,new Float[]{6f,6f,4f,4f});
        mPresenter.getBpartners(bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });

    }

    @OnClick({R.id.bt_receive_list_query, R.id.bt_batch_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_receive_list_query:
                mAdapter.getData().clear();
                mAdapter.initSelects();
                String asnNo = etReceiveListPackageDocumentNo.getText().toString();
                String productName = tietProductName.getText().toString();
                JSONObject data = new JSONObject();
                data.put("page", "receive");//
                data.put("asnType", asnType);
                if (!asnNo.isEmpty()) {
                    data.put("deliveryNo", asnNo);
                }
                if (dateTime > 0) {
                    String dataArrivedFrom = TimeDialogUtil.getBeforeDay(dateTime);
                    data.put("dataArrivedFrom", dataArrivedFrom);
                }
                if (!productName.isEmpty()) {
                    data.put("productName", productName);
                }
                if (bpartnerBean != null) {
                    data.put("orgID", bpartnerBean.getId());
                }
                mPresenter.getData(data);
                break;
          /*  case R.id.bt_receive_date_to:
                Calendar calendarTo = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_to,calendarTo);
                break;
            case R.id.bt_receive_date_from:
                Calendar calendarFrom = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_from,calendarFrom);
                break;*/
            case R.id.bt_batch_confirm:
                doBatchConfirm();
                break;
        }
    }

    private int itemPosition = 0;

    private void initRecyclerView() {
        mAdapter.setTitleBarView(tvShowSelect);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemPosition = position;
                receiveBean = (ReceiveBean) adapter.getData().get(position);
                startForResult(ReceiveDetailFragment.newInstance(receiveBean), REQUEST_CODE);
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
            }
        });
        mRecyclerView.setAdapter(mAdapter);

    }

    /**
     * 当有数据返回时，回调
     *
     * @param requestCode 返回状态码
     * @param resultCode  是否成功状态码
     * @param data        返回数据
     */
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mAdapter.remove(itemPosition);
        }

    }

    @Override
    public void updateContentList(List<ReceiveBean> receiveBeans) {
        if (receiveBeans.size() > 0) {
            mAdapter.addData(receiveBeans);
            mAdapter.notifyDataSetChanged();
            mLinearLayout.setVisibility(View.VISIBLE);
        } else {
            mLinearLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public <T extends View> T getViewByTag(int i) {
        switch (i) {
            case 1:
                return (T) btQuery;
            case 2:
                break;

        }
        return null;
    }

    private void doBatchConfirm() {
        final ArrayList<ReceiveBean> datas = mAdapter.getSelectedItem();
        if (datas.size() == 0) {
            DialogUtil.showMsgDialog(getContext(), "提示", "请选择至少一项");
            return;
        }
        new MaterialDialog.Builder(Objects.requireNonNull(getContext()))
                .title("批量收货")
                .content("确定要批量提交" + datas.size() + "个商品吗")
                .items(datas)
                // .iconRes(R.drawable.icon)
                .positiveText("确认")
                .negativeText("取消")
                //点击事件添加 方式1
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            // SparseArray<JSONArray> asnIds = new SparseArray<>();
                            //asnIds.put(datas.get(0).getAsnId(),new JSONArray());
                           /* for (ReceiveBean prb : datas) {
                                JSONArray asnLineIds = asnIds.get(prb.getAsnId());
                                if(asnLineIds!=null){
                                    asnLineIds.add(prb.getAsnLineId());
                                }else{
                                    asnLineIds = new JSONArray();
                                    asnLineIds.add(prb.getAsnLineId());
                                    asnIds.put(prb.getAsnId(),asnLineIds);
                                }
                            }*/
                            // int asnLineId = receiveBean.getAsnLineId();
                            JSONObject data = new JSONObject();
                            JSONArray receive = new JSONArray();
                            JSONArray asnLineId = new JSONArray();
                            for (ReceiveBean prb : datas) {

                                asnLineId.add(prb.getAsnLineId());
                            }
                            JSONObject asnLineIds = new JSONObject();
                            asnLineIds.put("asnLineId", asnLineId);
                            receive.add(asnLineIds);
                            data.put("recieve", receive);//
                            mPresenter.doBatchConfirm(data,()->{
                               for(int i: mAdapter.getSelectedItemPosition()){
                                      mAdapter.remove(i);
                               }
                                showMessage("处理成功！");

                            });
                            dialog.dismiss();
                            // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                        } else if (which == DialogAction.NEGATIVE) {
                            // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    }
                })
                .show();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            mCommonToolbar.setTitle("收货查询");
            mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
                pop();
                l.setOnClickListener(null);
                if (getActivity() != null) {
                    _mActivity.finish();
                }

            });
        }
        super.onHiddenChanged(hidden);

    }
}
